<template>
  <div class="page-card">
    <div class="table-toolbar">
      <el-input
        v-model="search"
        placeholder="输入教室名称或编号"
        clearable
        style="max-width: 240px"
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="openDialog()">
        <el-icon><Plus /></el-icon>
        新增教室
      </el-button>
    </div>

    <el-table :data="classrooms" border v-loading="loading">
      <el-table-column prop="classroom_code" label="教室编号" width="120" />
      <el-table-column prop="classroom_name" label="教室名称" width="160" />
      <el-table-column label="楼栋" width="120">
        <template #default="{ row }">
          {{ row.building_no }}号楼
        </template>
      </el-table-column>
      <el-table-column label="楼层" width="80">
        <template #default="{ row }">
          {{ row.floor_no }}层
        </template>
      </el-table-column>
      <el-table-column prop="capacity" label="容量" width="80" />
      <el-table-column label="设备" width="120">
        <template #default="{ row }">
          {{ getRoomTypeText(row.room_type) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '可用' : '不可用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="openDialog(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pagination.size"
        :current-page="pagination.page"
        :total="pagination.total"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="560px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="教室编号" prop="classroom_code">
          <el-input v-model="form.classroom_code" />
        </el-form-item>
        <el-form-item label="教室名称" prop="classroom_name">
          <el-input v-model="form.classroom_name" />
        </el-form-item>
        <el-form-item label="楼栋号" prop="building_no">
          <el-input-number v-model="form.building_no" :min="1" :max="20" />
        </el-form-item>
        <el-form-item label="楼层号" prop="floor_no">
          <el-input-number v-model="form.floor_no" :min="1" :max="20" />
        </el-form-item>
        <el-form-item label="房间号" prop="room_no">
          <el-input-number v-model="form.room_no" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input-number v-model="form.capacity" :min="10" :max="200" />
        </el-form-item>
        <el-form-item label="教室类型" prop="room_type">
          <el-select v-model="form.room_type">
            <el-option v-for="item in roomTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option v-for="item in classroomStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { createClassroom, deleteClassroom, getClassroomList, updateClassroom } from '@/api/academic'
import type { Classroom } from '@/types/academic'
import { classroomStatusOptions, roomTypeOptions } from '@/constants/options'

const loading = ref(false)
const saving = ref(false)
const classrooms = ref<Classroom[]>([])
const search = ref('')
const pagination = reactive({ page: 1, size: 10, total: 0 })

const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
  id: 0,
  classroom_code: '',
  classroom_name: '',
  building_no: 1,
  floor_no: 1,
  room_no: 1,
  capacity: 50,
  room_type: 1,
  status: 1
})

const rules: FormRules = {
  classroom_code: [{ required: true, message: '请输入教室编号', trigger: 'blur' }],
  classroom_name: [{ required: true, message: '请输入教室名称', trigger: 'blur' }]
}

const dialogTitle = computed(() => (isEdit.value ? '编辑教室' : '新增教室'))

// 获取教室类型文本
const getRoomTypeText = (type: number) => {
  const roomType = roomTypeOptions.find(item => item.value === type)
  return roomType ? roomType.label : '未知类型'
}

const loadClassrooms = async () => {
  loading.value = true
  try {
    const skip = (pagination.page - 1) * pagination.size
    const res = await getClassroomList({ skip, limit: pagination.size })
    const keyword = search.value.trim().toLowerCase()
    classrooms.value = res.items.filter((item: any) => {
      if (!keyword) return true
      return (
        item.classroom_name.toLowerCase().includes(keyword) ||
        item.classroom_no.toLowerCase().includes(keyword) ||
        item.building.toLowerCase().includes(keyword)
      )
    })
    pagination.total = keyword ? classrooms.value.length : res.total
  } catch (error: any) {
    ElMessage.error(error?.message || '加载教室数据失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadClassrooms()
}

const handleSearch = () => {
  pagination.page = 1
  loadClassrooms()
}

const resetForm = () => {
  Object.assign(form, {
    id: 0,
    classroom_code: '',
    classroom_name: '',
    building_no: 1,
    floor_no: 1,
    room_no: 1,
    capacity: 50,
    room_type: 1,
    status: 1
  })
  formRef.value?.clearValidate()
}

const openDialog = (row?: Classroom) => {
  resetForm()
  if (row) {
    isEdit.value = true
    Object.assign(form, row)
  } else {
    isEdit.value = false
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  saving.value = true
  try {
    if (isEdit.value) {
      await updateClassroom(form.id, form)
    } else {
      await createClassroom(form)
    }
    ElMessage.success('保存成功')
    dialogVisible.value = false
    loadClassrooms()
  } catch (error: any) {
    ElMessage.error(error?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const handleDelete = async (row: Classroom) => {
  await ElMessageBox.confirm(`确认删除教室【${row.classroom_name}】吗？`, '提示', { type: 'warning' })
  try {
    await deleteClassroom(row.id)
    ElMessage.success('已删除')
    loadClassrooms()
  } catch (error: any) {
    ElMessage.error(error?.message || '删除失败')
  }
}

onMounted(() => {
  loadClassrooms()
})
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: var(--spacing-md);
}
</style>